<template>
  <div class="class-management">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">
            <el-icon class="title-icon"><User /></el-icon>
            班级管理
          </h1>
          <p class="page-subtitle">管理系统中的所有班级信息</p>
        </div>
        <div class="action-buttons">
          <el-button @click="refresh" :icon="Refresh" size="large" class="refresh-btn">
            刷新
          </el-button>
          <el-button type="primary" @click="handleCreate" :icon="Plus" size="large">
            新建班级
          </el-button>
        </div>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="filter-left">
        <el-input
          v-model="search"
          placeholder="搜索班级名称或编码"
          clearable
          size="large"
          style="width: 280px"
          @input="handleSearch"
          :prefix-icon="Search"
          class="search-input"
        />
        <el-select
          v-model="selectedYear"
          placeholder="学年筛选"
          clearable
          size="large"
          style="width: 180px"
          @change="handleYearChange"
          class="filter-select"
        >
          <el-option
            v-for="year in academicYears"
            :key="year.id"
            :label="year.year_name"
            :value="year.id"
          />
        </el-select>
        <el-select
          v-model="selectedStatus"
          placeholder="状态筛选"
          clearable
          size="large"
          style="width: 140px"
          @change="handleStatusChange"
          class="filter-select"
        >
          <el-option label="启用" :value="1" />
          <el-option label="停用" :value="0" />
        </el-select>
      </div>
      <div class="filter-right">
        <span class="total-count">共 {{ pagination.total }} 个班级</span>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="filteredClasses"
        v-loading="loading"
        style="width: 100%"
        :default-sort="{ prop: 'create_time', order: 'descending' }"
        class="data-table"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="class_code" label="班级编码" min-width="100" sortable>
          <template #header>
            <span class="column-header">班级编码</span>
          </template>
          <template #default="{ row }">
            <span class="code-text">{{ row.class_code }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="class_name" label="班级名称" min-width="120">
          <template #header>
            <span class="column-header">班级名称</span>
          </template>
          <template #default="{ row }">
            <span class="name-text">{{ row.class_name }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="学年信息" min-width="140">
          <template #header>
            <span class="column-header">学年信息</span>
          </template>
          <template #default="{ row }">
            <div class="academic-info">
              <span class="year-text">{{ getAcademicYearName(row.academic_year_id) }}</span>
              <span class="grade-label">{{ getGradeName(row.grade) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="班主任" min-width="130">
          <template #header>
            <span class="column-header">班主任</span>
          </template>
          <template #default="{ row }">
            <div class="teacher-info">
              <el-avatar :size="32" class="teacher-avatar">
                {{ getTeacherName(row.head_teacher_id).charAt(0) }}
              </el-avatar>
              <span class="teacher-name">{{ getTeacherName(row.head_teacher_id) }}</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column label="学生人数" min-width="100" align="center">
          <template #header>
            <span class="column-header">学生人数</span>
          </template>
          <template #default="{ row }">
            <span class="student-count" :class="{ 'zero-count': row.student_count === 0 }">
              {{ row.student_count || 0 }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column label="状态" min-width="90" align="center">
          <template #header>
            <span class="column-header">状态</span>
          </template>
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 1 ? 'success' : 'info'" 
              size="small"
              class="status-tag"
            >
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="创建时间" min-width="150" sortable>
          <template #header>
            <span class="column-header">创建时间</span>
          </template>
          <template #default="{ row }">
            <span class="time-text">{{ formatTime(row.create_time) }}</span>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #header>
            <span class="column-header">操作</span>
          </template>
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                size="small" 
                @click="handleEdit(row)" 
                :icon="Edit"
                link
                class="action-btn"
                style="padding: 4px 6px; font-size: 12px;"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                :type="row.status === 1 ? 'warning' : 'success'"
                @click="handleToggleStatus(row)"
                :icon="Switch"
                link
                class="action-btn"
                style="padding: 4px 6px; font-size: 12px;"
              >
                {{ row.status === 1 ? '停用' : '启用' }}
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="handleDelete(row)" 
                :icon="Delete"
                link
                class="action-btn"
                style="padding: 4px 6px; font-size: 12px;"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 班级编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="班级编码" prop="class_code">
          <el-input v-model="formData.class_code" placeholder="请输入班级编码" />
        </el-form-item>
        <el-form-item label="班级序号" prop="class_no">
          <el-input-number v-model="formData.class_no" :min="1" :max="50" placeholder="请输入班级序号" />
        </el-form-item>
        <el-form-item label="班级名称" prop="class_name">
          <el-input v-model="formData.class_name" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="学年" prop="academic_year_id">
          <el-select v-model="formData.academic_year_id" placeholder="请选择学年" style="width: 100%">
            <el-option
              v-for="year in academicYears"
              :key="year.id"
              :label="year.year_name"
              :value="year.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-select v-model="formData.grade" placeholder="请选择年级" style="width: 100%">
            <el-option v-for="grade in grades" :key="grade.value" :label="grade.label" :value="grade.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="班主任" prop="head_teacher_id">
          <el-select v-model="formData.head_teacher_id" placeholder="请选择班主任" style="width: 100%">
            <el-option
              v-for="teacher in teachers"
              :key="teacher.id"
              :label="teacher.teacher_name"
              :value="teacher.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Plus,
  Refresh,
  Search,
  Edit,
  Delete,
  Switch,
  User
} from '@element-plus/icons-vue'
import {
  getClassList,
  createClassItem,
  updateClassItem,
  deleteClassItem,
  type ClassItem,
  type ClassPayload
} from '@/api/academic'
import { getAcademicYearList, type AcademicYear } from '@/api/academic'
import { getTeacherList, type Teacher } from '@/api/users'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitting = ref(false)
const search = ref('')
const selectedYear = ref<number | null>(null)
const selectedStatus = ref<number | null>(null)
const formRef = ref<FormInstance>()

const classes = ref<ClassItem[]>([])
const academicYears = ref<AcademicYear[]>([])
const teachers = ref<Teacher[]>([])

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const formData = reactive<ClassPayload>({
  class_code: '',
  class_name: '',
  academic_year_id: 0,
  grade: 1,
  class_no: 1,
  head_teacher_id: undefined,
  status: 1
})

const currentEditId = ref<number | null>(null)

// 计算属性
const dialogTitle = computed(() => currentEditId.value ? '编辑班级' : '新建班级')

const filteredClasses = computed(() => {
  let result = classes.value
  
  if (search.value.trim()) {
    const keyword = search.value.trim().toLowerCase()
    result = result.filter((item: any) => 
      item.class_name.toLowerCase().includes(keyword) ||
      item.class_no.toString().toLowerCase().includes(keyword)
    )
  }
  
  if (selectedYear.value) {
    result = result.filter((item: any) => item.academic_year_id === selectedYear.value)
  }
  
  if (selectedStatus.value !== null) {
    result = result.filter((item: any) => item.status === selectedStatus.value)
  }
  
  return result
})

// 表单验证规则
const formRules: FormRules = {
  class_code: [
    { required: true, message: '请输入班级编码', trigger: 'blur' }
  ],
  class_no: [
    { required: true, message: '请输入班级序号', trigger: 'blur' }
  ],
  class_name: [
    { required: true, message: '请输入班级名称', trigger: 'blur' }
  ],
  academic_year_id: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  grade: [
    { required: true, message: '请选择年级', trigger: 'change' }
  ]
}

// 方法
const loadClasses = async () => {
  loading.value = true
  try {
    const skip = (pagination.page - 1) * pagination.size
    const res = await getClassList({ skip, limit: pagination.size })
    classes.value = res.items
    pagination.total = res.total
  } catch (error: any) {
    ElMessage.error(error?.message || '加载班级数据失败')
  } finally {
    loading.value = false
  }
}

const loadAcademicYears = async () => {
  try {
    const res = await getAcademicYearList({ limit: 100 })
    academicYears.value = res.items
  } catch (error) {
    console.error('加载学年数据失败', error)
  }
}

const loadTeachers = async () => {
  try {
    const res = await getTeacherList({ limit: 500 })
    teachers.value = res.items
  } catch (error) {
    console.error('加载教师数据失败', error)
  }
}

const handleCreate = () => {
  currentEditId.value = null
  Object.assign(formData, {
    class_code: '',
    class_name: '',
    academic_year_id: 0,
    grade: 1,
    class_no: 1,
    head_teacher_id: undefined,
    status: 1
  })
  dialogVisible.value = true
}

const handleEdit = (row: ClassItem) => {
  currentEditId.value = row.id
  Object.assign(formData, {
    class_code: row.class_code,
    class_name: row.class_name,
    academic_year_id: row.academic_year_id,
    grade: row.grade,
    class_no: row.class_no,
    head_teacher_id: row.head_teacher_id,
    status: row.status
  })
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (currentEditId.value) {
      await updateClassItem(currentEditId.value, formData)
      ElMessage.success('班级更新成功')
    } else {
      await createClassItem(formData)
      ElMessage.success('班级创建成功')
    }
    
    dialogVisible.value = false
    await loadClasses()
  } catch (error: any) {
    if (error?.errors) {
      // 表单验证错误
      return
    }
    ElMessage.error(error?.message || '操作失败')
  } finally {
    submitting.value = false
  }
}

const handleToggleStatus = async (row: ClassItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? '停用' : '启用'}班级 "${row.class_name}" 吗？`,
      '提示',
      { type: 'warning' }
    )
    
    await updateClassItem(row.id, { 
      ...row, 
      status: row.status === 1 ? 0 : 1,
      classroom_id: row.classroom_id || undefined
    })
    ElMessage.success('状态更新成功')
    await loadClasses()
  } catch (error: any) {
    if (error === 'cancel') return
    ElMessage.error(error?.message || '操作失败')
  }
}

const handleDelete = async (row: ClassItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除班级 "${row.class_name}" 吗？此操作不可恢复。`,
      '警告',
      { type: 'warning' }
    )
    
    await deleteClassItem(row.id)
    ElMessage.success('班级删除成功')
    await loadClasses()
  } catch (error: any) {
    if (error === 'cancel') return
    ElMessage.error(error?.message || '删除失败')
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleSearch = () => {
  pagination.page = 1
}

const handleYearChange = () => {
  pagination.page = 1
}

const handleStatusChange = () => {
  pagination.page = 1
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadClasses()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadClasses()
}

const refresh = () => {
  search.value = ''
  selectedYear.value = null
  selectedStatus.value = null
  pagination.page = 1
  loadClasses()
}

// 年级选项
const grades = [
  { value: 1, label: '一年级' },
  { value: 2, label: '二年级' },
  { value: 3, label: '三年级' },
  { value: 4, label: '四年级' },
  { value: 5, label: '五年级' },
  { value: 6, label: '六年级' }
]

const getAcademicYearName = (id: number) => {
  const year = academicYears.value.find((y: any) => y.id === id)
  return year ? year.year_name : '未知学年'
}

const getGradeName = (grade: number) => {
  const gradeInfo = grades.find(g => g.value === grade)
  return gradeInfo ? gradeInfo.label : '未知年级'
}

const getTeacherName = (teacherId?: number) => {
  if (!teacherId) return '未分配'
  const teacher = teachers.value.find((t: any) => t.id === teacherId)
  return teacher ? teacher.teacher_name : '未知教师'
}

// 格式化时间显示
const formatTime = (time: string) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 表格行类名
const tableRowClassName = ({ row }: { row: any }) => {
  return row.status === 0 ? 'disabled-row' : ''
}

// 生命周期
onMounted(() => {
  loadClasses()
  loadAcademicYears()
  loadTeachers()
})
</script>

<style scoped>
.class-management {
  padding: 24px;
  background: #f8f9fa;
  min-height: 100vh;
}

/* 页面标题区域 */
.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  padding: 32px 40px;
  margin-bottom: 24px;
  color: white;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.2);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.page-title {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.title-icon {
  font-size: 32px;
}

.page-subtitle {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
  font-weight: 400;
}

.action-buttons {
  display: flex;
  gap: 12px;
  align-items: center;
}

.refresh-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.refresh-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 筛选工具栏 */
.filter-toolbar {
  background: white;
  border-radius: 12px;
  padding: 20px 24px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

.filter-left {
  display: flex;
  gap: 16px;
  align-items: center;
}

.search-input {
  border-radius: 8px;
}

.filter-select {
  border-radius: 8px;
}

.filter-right {
  display: flex;
  align-items: center;
}

.total-count {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

/* 表格容器 */
.table-container {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

.data-table {
  --el-table-border-color: #e4e7ed;
  --el-table-header-bg-color: #f5f7fa;
}

.data-table :deep(.el-table__header) {
  background: #f5f7fa;
}

.data-table :deep(.el-table__header th) {
  background: #f5f7fa;
  color: #303133;
  font-weight: 600;
  font-size: 14px;
}

.column-header {
  font-weight: 600;
  color: #303133;
}

/* 表格行样式 */
.data-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.data-table :deep(.el-table__row:hover) {
  background: #f0f2f5;
  transform: translateY(-1px);
}

/* 自定义单元格样式 */
.code-text {
  font-family: 'Monaco', 'Consolas', monospace;
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.name-section {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.name-text {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.class-no {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.academic-info {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.year-text {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.grade-label {
  color: #909399;
  font-size: 12px;
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.teacher-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.teacher-avatar {
  background: linear-gradient(45deg, #409eff, #67c23a);
  font-weight: 600;
}

.teacher-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
}

.student-count {
  font-weight: 600;
  font-size: 16px;
  color: #67c23a;
}

.student-count.zero-count {
  color: #c0c4cc;
}

.status-tag {
  border-radius: 4px;
  font-weight: 500;
  padding: 4px 8px;
}

.time-text {
  color: #606266;
  font-size: 13px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 6px;
  flex-wrap: wrap;
}

.action-btn {
  padding: 6px 10px;
  font-weight: 500;
  font-size: 12px;
  min-width: auto;
}

/* 分页样式 */
.pagination {
  background: white;
  border-radius: 12px;
  padding: 20px 24px;
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-left {
    flex-wrap: wrap;
  }
  
  .filter-toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-left {
    justify-content: space-between;
  }
}

@media (max-width: 768px) {
  .page-header {
    padding: 24px 20px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }
  
  .action-buttons {
    justify-content: center;
  }
}
</style>